#include <iostream>
#include <memory>
#include "TcpServer.hpp"
#include "Common.hpp"
#include "Protocol_Netcal.hpp"


void Usage(std::string cmd)
{
    std::cout << "please use : " << cmd << " server_ip server_port" << std::endl;
    exit(USAGE_ERROR);
}

void TcpClientGetInput(int* px, int* py, char* opr){
    std::cout << "please input left_num : " ;
    std::cin >> *px;

    std::cout << "please input opr : " ;
    std::cin >> *opr;

    std::cout << "please input right_num : " ;
    std::cin >> *py;

}


// ./Client_NetCal.exe server_ip server_port
int main(int argc, char* argv[]){
    if (argc != 3)
        Usage(argv[0]);

    //服务器ip
    std::string server_ip = argv[1];
    //服务器端口号
    uint16_t server_port = std::stoi(argv[2]);

    //创建客户端套接字
    std::shared_ptr<Socket> pSocket = std::make_shared<TcpSocket>();   
    pSocket->CreateClientTcpSocket();

    //bind不用显示做，accrpt也不用，listen也不用！
    //connect的时候系统自动做好处理了！
    InetAddr server(server_ip, server_port);
    pSocket->Connect(server); 

    //定义一个协议对象
    std::shared_ptr<Protocol_Netcal> pro = std::make_shared<Protocol_Netcal>();

    std::string inbuffer;

    while(1){
        int left_num = 0, right_num = 0;
        char opr = '0';

        TcpClientGetInput(&left_num, &right_num, &opr);

        //1.构造一个Request的对应的序列化 + Encode字符串
        std::string req_str = pro->BulidRequestStr(left_num, right_num, opr);

        //2.把这个字符串进行发送
        pSocket->Send(req_str);

        //3.获取Response（和GetRequest类似） -> 完成读取 + Decode + 反序列化
        Response resp;
        if(!pro->GetResponse(pSocket, resp, &inbuffer)) break;

        //4.展示结果
        resp.Show();

       









        /* //1.构造一个请求
        Request req(left_num, right_num, opr);
        //2.发之前，需要进行序列化 + Encode
        std::string json_str = req.Serialize();
        std::string req_str = pro->Encode(json_str);


        //4.发送
        pSocket->Send(req_str);


        //5.接收序列化的应答字符串
        pSocket->Recv(&inbuffer);

        std::cout << inbuffer << std::endl;

        //6.使用之前，需要进行Decode
        std::string get_str;
        bool ok = pro->Decode(inbuffer, &get_str);

        if(!ok) continue;

        //7.构建应答
        Response resp;
        resp.DeSerialize(get_str);

        //8.得到结果，展示
        resp.Show(); */

        





    }
    //9.关闭套接字文件描述符
    //pSocket->Close();


    //5.关闭套接字文件描述符
    pSocket->Close();
    return 0;
}